# include <stdio.h>
# include <sys/stat.h>
# include <fcntl.h>
# define uchar unsigned char
# define uint unsigned int
# include <unistd.h>
# include <sys/mman.h>
struct image{
	char bmppath[20];
	int x;
	int y;
	int w;
	int h;
};

struct image bmp_image[10] = {
	{.bmppath = "a.bmp",.x=0,.y=0,.w=100,.h=480},
	{.bmppath = "b.bmp",.x=100,.y=0,.w=100,.h=480},
	{.bmppath = "c.bmp",.x=200,.y=0,.w=100,.h=480},
	{.bmppath = "d.bmp",.x=300,.y=0,.w=100,.h=480},
	{.bmppath = "e.bmp",.x=400,.y=0,.w=100,.h=480},
	{.bmppath = "f.bmp",.x=500,.y=0,.w=100,.h=480},
	{.bmppath = "g.bmp",.x=600,.y=0,.w=100,.h=480},
	{.bmppath = "h.bmp",.x=700,.y=0,.w=100,.h=480}
};
	
int open_jugg(int i)
{
	//char *j = "oepn_parm";
	//printf("%s=%d\n",j,i);
	if (i< 0)
	{
		//printf("failure\n");
		return 0;
	}
	else
	{
		//printf("success\n");
		return 1;
	}
}

// lcd显示函数 定义起始坐标x、y，图片宽高w、h，颜色B、G、R，透明度tou
int lcd_display(int x, int y, int w, int h, int b, int g, int r, int tou)
{
	int lcd = open("/dev/fb0",O_RDWR);
	printf("LCD=%d\n",open_jugg(lcd));
	
	int i,j;
	char *buf = mmap(NULL,800*480*4,PROT_WRITE,MAP_SHARED,lcd,0);
	
	for(j=y;j<(y+h);j++)
	{
		for(i=x;i<(x+w);i++)
		{
			buf[0+4*i+800*4*j] = b;
			buf[1+4*i+800*4*j] = g;
			buf[2+4*i+800*4*j] = r;
			buf[3+4*i+800*4*j] = tou;	
			//write(lcd,buf,4);	
		}
		//write(lcd,buf,4*800);
	}
	write(lcd,buf,800*480*4);	
	close(lcd);
	munmap(buf,800*480*4); //释放内存
	return 0;
}

// lcd显示图片 定义指针bmp图片路径 起始坐标 宽 高 透明度
int lcd_dis_bmp(char *bmppath, int x, int y, int w, int h, int tou)
{
	int lcd = open("/dev/fb0",O_RDWR);
	printf("LCD=%d\n",open_jugg(lcd));
	int bmp = open(bmppath,O_RDWR);
	printf("BMP=%d\n",open_jugg(bmp));
	
	lseek(bmp,54,SEEK_SET);
	char bmpbuf[w*h*3];
	read(bmp,bmpbuf,w*h*3);
	
	int i,j;
	char *buf = mmap(NULL,800*480*4,PROT_WRITE,MAP_SHARED,lcd,0);
	
	for(j=y;j<y+h;j++)
	{
		for(i=x;i<x+w;i++)
		{
			buf[0+4*i+800*4*j] = bmpbuf[0+3*(i-x)+w*3*(h-1-j+y)];
			buf[1+4*i+800*4*j] = bmpbuf[1+3*(i-x)+w*3*(h-1-j+y)];
			buf[2+4*i+800*4*j] = bmpbuf[2+3*(i-x)+w*3*(h-1-j+y)];
			buf[3+4*i+800*4*j] = tou;
			//write(lcd,buf,4);	
		}
		//write(lcd,buf,4*800);
	}
	write(lcd,buf,800*480*4);	
	close(lcd);
	close(bmp);
	munmap(buf,800*480*4); //释放内存	
}

int main(void)
{
	// char bmp[10][10]={"1.bmp","2.bmp","3.bmp","4.bmp","5.bmp","6.bmp","7.bmp","8.bmp","9.bmp","10.bmp"};
	// lcd_dis_bmp("200200.bmp",100,100,200,200,0);
	// sleep(5);
	while(1)
	{
		int i;
		for(i=0;i<10;i++)
		{
			lcd_dis_bmp(bmp_image[i].bmppath,bmp_image[i].x,bmp_image[i].y,bmp_image[i].w,bmp_image[i].h,0);			
			sleep(0.5);
		}		
	}
	//lcd_display(200,300,300,100,127,0,128,0);
	return 0;
}